package 享元模式;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MemoryFactory {
    //内存对象列表
    private static List<Memory> memoryList = new ArrayList<Memory>();

    public static Memory geyMemory(int size){
        Memory memory = null;
        for (int i = 0; i < memoryList.size(); i++) {
            memory = memoryList.get(i);
            //如果存在和需求size一样大小并且未使用的内存块，则直接返回
            if (memory.getSize()==size&&memory.isIsused()==false) {
                memory.setIsused(true);
                memoryList.set(i,memory);
                System.out.println("使用："+memory.toString());
                break;
            }
        }
        if(memory==null){
            memory = new Memory(32,false,UUID.randomUUID().toString());
            System.out.println("创建："+memory.toString());
            memoryList.add(memory);
        }
        return memory;
    }

    //释放内存
    public static void releaseMemory(String id){
        for (int i = 0; i < memoryList.size(); i++) {
            Memory memory = memoryList.get(i);
            if (memory.getId().equals(id)) {
                memory.setIsused(false);
                memoryList.set(i,memory);
                System.out.println("释放："+memory.toString());
                break;
            }
        }
    }
}
